package com.leve.admin.scheduledTasks;

import com.leve.admin.common.JedisUtil;
import com.leve.admin.domain.Ghost;
import com.leve.admin.service.ReceiverService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class BatchJob {
    @Autowired
    private ReceiverService receiverService;

    @Resource
    @Qualifier("landTemplate")
    private MongoOperations landMongoOperations;


    @Scheduled(fixedRate = 10000)
    public void selectNewUser() {
        //find new user
        Jedis redis = JedisUtil.getJedis();
        long ghostCount = landMongoOperations.getCollection("ghost").count();
        String ldoGhostCount = redis.get("ghostCount");
        if (ldoGhostCount == null) {
            redis.set("ghostCount", ghostCount + "");
        } else {
            Long aLong = new Long(ldoGhostCount);
            long falg = ghostCount - aLong;
            if (falg > 0) {
                Aggregation agg = Aggregation.newAggregation(
                        //分页操作，pageNumber为当前页数，pageSize为每页显示条数
                        Aggregation.skip(aLong),
                        Aggregation.limit(falg)
                );
                AggregationResults<Ghost> ghost = landMongoOperations.aggregate(agg, "ghost", Ghost.class);
                List<Ghost> ghosts = ghost.getMappedResults();
                log.info("========= ghosts ========= {} ", ghosts.size());
                for (Ghost g : ghosts) {
                    Runnable r = () -> {
                        try {
                            receiverService.toSay(g);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    };
                    r.run();

                }
                redis.set("ghostCount", ghostCount + "");
            }
            JedisUtil.returnBrokenResource(redis);
        }
        log.info("current ghostCount {} , redis in ghostCount {} ", ghostCount, ldoGhostCount);
    }

}
